from BaseBlocks import ImagePipeline,ImagePreview
from CommonBlocks import ImageCapture_OpenCV,ImageProcessor_OtsuThreshould,ImageProcessor_ConvertToGray,ImageProcessor_HSVRange
from ArgumentSettings import ArgumentSettingWindow
from PyQt6.QtWidgets import QMainWindow,QApplication
import os,sys
import json
import numpy as np

class ComputerVisionSystem():
    def __init__(self,
                 pipeline: ImagePipeline,
                 argumentJsonPath: str
                 ):
        self.argumentJsonPath = argumentJsonPath

        self.pipeline = pipeline
        self.pipeline.setup()

        self.requiredArgs = pipeline.requiredArgs
        for arg in self.requiredArgs:
            #设置全部置0为默认
            self.pipeline.setArgument(arg,0)
        self.pipeline.renderPreview = self.renderQtPixmap
        self.qtApp = QApplication(sys.argv)
        self.settingWindow = ArgumentSettingWindow(arguments=self.requiredArgs,previews=self.pipeline.previewNames,argumentUpdateCallback=pipeline.setArguments,saveArgumentsCallback=self.saveJsonArguments)
    
    def renderQtPixmap(self,name: str,image:np.ndarray):
        self.settingWindow.imageUpdateSignal.emit(name,image)
    
    def loadJsonArguments(self):
        if os.path.isfile(self.argumentJsonPath):
            with open(self.argumentJsonPath,'r') as f:
                arguments = json.loads(f.read())
                self.pipeline.setArguments(arguments)
                self.settingWindow.setArguments(arguments)
                f.close()
    def saveJsonArguments(self):
        print('Configuration saved.')
        with open(self.argumentJsonPath,'w') as f:
            f.write(json.dumps(self.pipeline.getArguments()))
            f.close()
    def exec(self):
        self.pipeline.start()
        self.settingWindow.show()
        return self.qtApp.exec()

    def cleanup(self):
        self.pipeline.stop()

if __name__ == '__main__':
    pipeline = ImagePipeline(ImageCapture_OpenCV(0),
                            [   
                                ImagePreview('imagePreview1'),
                                ImageProcessor_HSVRange('HSVRange1'),
                                ImagePreview('imagePreview2')
                            ],
                            5
                            )
    
    system = ComputerVisionSystem(pipeline,'arguments.json')
    system.loadJsonArguments()
    retCode = system.exec()
    system.cleanup()
    sys.exit(retCode)